<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Models;

use DateTimeInterface;
use Dcat\Admin\Admin;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class GroupOrderProduct extends Model
{
    use HasFactory;
    use \App\Traits\ModelTraits\LogsActivityTrait;

    //protected $table = '';
    //protected $primaryKey='';
    //public $incrementing = false //使用非递增或者非数字的主键设置false
    //public $timestamps = false; //关闭自动时间维护
    //protected $fillable = ['']; //可被批量赋值
    protected $guarded = []; //不被批量赋值 空为全部可以赋值

    //protected $dates = ['deleted_at'];
    //protected $hidden = ['user_password'];
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'main_image' => 'array',
    ];

    protected $appends = [
        'session_number',
    ];

    public function getSessionNumberAttribute($value)
    {
        if (blank(Admin::user())) {
            $gp = GroupOrder::query()
                ->select('product_id', 'id', 'number')
                ->where('status', 1)
                ->where('product_id', $this->id)
                ->get();
            return $this->attributes['session_number'] = $gp->sum('number');
        }
    }

    public function checkTheStock($number): bool
    {
        if ($this->stock - $number < 0) {
            return false;
        }
        return true;
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}
